package com.zmj.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * ClassExtraUtil
 *
 * @author chiyu
 */
@Slf4j
public class ClassExtraUtil {

    private ClassExtraUtil() {
        throw new UnsupportedOperationException();
    }

    /**
     * 根据属性名获取属性值
     *
     * @param fieldName fieldName
     * @param o         o
     * @return Object
     */
    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String getFun = "get" + StringUtils.capitalize(fieldName);
            Method method = o.getClass().getMethod(getFun);
            return method.invoke(o);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据属性名设置属性值
     *
     * @param fieldName fieldName
     * @param o         o
     * @param value     set值
     */
    public static void setFieldValueByName(String fieldName, Object o, Object value) {
        try {
            String setFun = "set" + StringUtils.capitalize(fieldName);
            Method method = o.getClass().getMethod(setFun, value.getClass());
            method.invoke(o, value);
        } catch (Exception e) {
            log.warn(e.getMessage(), e);

        }
    }
}
